package com.cg.proxy;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.SourceLocation;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Field;
import java.util.stream.Stream;

/**
 * @author cheyinbo
 * @description TODO
 * @date 2021/8/18 14:29
 */
@EnableAspectJAutoProxy
@Aspect
@Component
public class UserProxy {

    @Pointcut(value = "execution(public * com.cg.service..*.*(..))")
    public void pointCut(){}

    @Before(value = "pointCut()")
    public void before(JoinPoint joinPoint){
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        HttpServletRequest httpServletRequest = ((ServletRequestAttributes)requestAttributes).getRequest();
        String method = httpServletRequest.getRemoteAddr();
        System.out.println(method);
        System.out.println(joinPoint.getArgs()[0]);
        System.out.println("前置通知...");
    }

    @After(value = "pointCut()")
    public void after(JoinPoint joinPoint){
        System.out.println("后置通知...");
    }

    @AfterThrowing(value = "pointCut()")
    public void throwing(JoinPoint joinPoint){
        System.out.println("异常通知...");
    }

    @AfterReturning(value = "pointCut()")
    public void afterReturning(JoinPoint joinPoint){
        System.out.println("后置通知(增强)...");
    }

//    @Around(value = "pointCut()")
//    public Object around(ProceedingJoinPoint proceedingJoinPoint) {
//        System.out.println("前置通知");
//        Signature signature = proceedingJoinPoint.getSignature();
//        System.out.println("方法名称:" + signature.getName());
//        Object[] args = proceedingJoinPoint.getArgs();
//        Stream.of(args).forEach(o -> System.out.println("参数："+ o));
//
//        Object proceed = null;
//        try {
//            System.out.println("方法执行前>>>>>>>>>>>>>>");
//            proceed = proceedingJoinPoint.proceed();
//            System.out.println("方法执行后>>>>>>>>>>>>>>");
//            System.out.println("方法返回值:"+proceed);
//        }catch (Throwable throwable) {
//            System.out.println("异常通知");
//        }
//        System.out.println("后置通知");
//        return proceed;
//    }

}
